package com.macro.mall.controller;

import com.github.pagehelper.PageHelper;
import com.macro.mall.annotationUtil.CurrentUser;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.dao.PmsSkuStockDao;
import com.macro.mall.dto.PmsProductDTO;
import com.macro.mall.dto.PmsSkuStockDTO;
import com.macro.mall.mapper.PmsProductMapper;
import com.macro.mall.mapper.PmsSkuStockMapper;
import com.macro.mall.mapper.UmsStoreMapper;
import com.macro.mall.model.*;
import com.quyum.mall.market.config.RedisKey;
import com.quyum.mall.market.dto.MarketSmsRoundDTO;
import com.quyum.mall.market.dto.MarketSmsRoundProductDTO;
import com.quyum.mall.market.entity.MarketSmsRound;
import com.quyum.mall.market.entity.MarketSmsRoundProduct;
import com.quyum.mall.market.example.MarketSmsRoundProductExample;
import com.quyum.mall.market.mapper.MarketSmsRoundMapper;
import com.quyum.mall.market.mapper.MarketSmsRoundProductMapper;
import com.quyum.mall.market.service.bean.RoundService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 添加活动场次
 * @author zhouboyu
 * @Date 2020年10月20日
 */
@Controller
@Api(tags = "SmsActivityController", description = "限时购场次管理")
@RequestMapping("/smsActivity")
public class SmsActivityController {
    @Autowired
    private RoundService roundService;
    @Autowired
    private MarketSmsRoundMapper roundMapper;
    @Autowired
    private MarketSmsRoundProductMapper roundProductMapper;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsSkuStockMapper stockMapper;
    @Autowired
    private PmsSkuStockDao skuStockDao;
    @Autowired
    private UmsStoreMapper storeMapper;
    @Autowired
    private RedisService redisService;
    @ApiOperation("添加场次")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@CurrentUser UmsAdmin currentUser, @RequestBody MarketSmsRoundDTO round) {
        MarketSmsRound ro = new MarketSmsRound();
        BeanUtils.copyProperties(round,ro);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ro.setUserId(currentUser.getId());
        try {
            ro.setStartTime(sdf.parse(round.getStartTimeStr()));
            ro.setEndTime(sdf.parse(round.getEndTimeStr()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(ro.getStartTime().before(new Date())){
            return CommonResult.failed("开始时间不能早于当前时间");
        }
        Long id = null;
        try {
            id = roundService.add(ro);
        } catch (ApiException e) {
            return CommonResult.failed(e.getMessage());
        }
        if(id.compareTo(0L)>0){
            return CommonResult.success(id);
        }else{
            return CommonResult.failed("保存失败，请重试");
        }
    }

    @ApiOperation("修改场次")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(@RequestBody MarketSmsRoundDTO round) {
        MarketSmsRound ro = new MarketSmsRound();
        BeanUtils.copyProperties(round,ro);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            ro.setStartTime(sdf.parse(round.getStartTimeStr()));
            ro.setEndTime(sdf.parse(round.getEndTimeStr()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String update = "";
        try {
            update= this.roundService.update(ro);
        } catch (ApiException e) {
            return CommonResult.failed(e.getMessage());
        }
        if (StringUtils.isBlank(update)) {
            return CommonResult.success(update);
        }else{
            return CommonResult.failed(update);
        }
    }


    @ApiOperation("删除场次")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@CurrentUser UmsAdmin admin,@RequestParam String ids) {
        String s = this.roundService.deleteAndProduct(admin.getId(),ids);
        if (StringUtils.isBlank(s)) {
            return CommonResult.success(s);
        }else{
            return CommonResult.failed(s);
        }
    }

    @ApiOperation("获取场次详情")
    @RequestMapping(value = "/getDetail", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<MarketSmsRound> getItem(Long id) {
        MarketSmsRound marketSmsRound = this.roundMapper.selectByPrimaryKey(id);
        if(marketSmsRound!=null){
            return CommonResult.success(marketSmsRound);
        }else{
            return CommonResult.failed("该活动场次不存在");
        }
    }

    @ApiOperation("添加活动下的商品")
    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult addProduct(@RequestBody MarketSmsRoundProduct product) {
        String s = this.roundService.addProduct(product, product.getRoundId());
        if(StringUtils.isNotBlank(s)){
          return  CommonResult.failed(s);
        }else {
            return  CommonResult.success(null);
        }
    }

    @ApiOperation("修改活动下的商品")
    @RequestMapping(value = "/updateProduct", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateProduct(@RequestBody MarketSmsRoundProduct product) {
        String s = this.roundService.updateProduct(product, product.getRoundId());
        if(StringUtils.isNotBlank(s)){
            return  CommonResult.failed(s);
        }else {
            return  CommonResult.success(null);
        }
    }

    @ApiOperation("修改活动下的商品")
    @RequestMapping(value = "/delProduct", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delProduct(@RequestParam String ids) {
        String s = this.roundService.deleteProduct(ids);
        if(StringUtils.isNotBlank(s)){
            return  CommonResult.failed(s);
        }else {
            return  CommonResult.success(null);
        }
    }

    @ApiOperation("修改活动下的商品")
    @RequestMapping(value = "/confirm", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult confirm(@RequestParam Long roundId) {
        String s = this.roundService.doLockStock(roundId);
        if(StringUtils.isNotBlank(s)){
            return  CommonResult.failed(s);
        }else {
            return  CommonResult.success(null);
        }
    }

    @ApiOperation("分页获取活动场次下的商品列表")
    @RequestMapping(value = "/listProductsByRoundId", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Map<String, Object>> list(Long roundId
            , @RequestParam(required = false,defaultValue = "1") Integer pageNum
            , @RequestParam(required = false,defaultValue = "5") Integer pageSize) {
        Map<String, Object> returnMap = new HashMap<>();
        CommonPage<Long> longCommonPage = this.roundService.selectByRoundId(roundId, pageNum, pageSize);
        List<Long> list = longCommonPage.getList();
        List<Long> skuIdList = new ArrayList<>();
        List<PmsProductDTO> res = new ArrayList<>();
        MarketSmsRound smsRound = this.roundMapper.selectByPrimaryKey(roundId);
        if(!CollectionUtils.isEmpty(list)){
            PmsProductExample example = new PmsProductExample();
            example.createCriteria().andIdIn(list);
            List<PmsProduct> pmsProducts = this.productMapper.selectByExample(example);
            if(!CollectionUtils.isEmpty(pmsProducts)){
                for (PmsProduct p:pmsProducts) {
                    PmsProductDTO productDTO = new PmsProductDTO();
                    BeanUtils.copyProperties(p,productDTO);
                    List<MarketSmsRoundProduct> marketSmsRoundProducts = new ArrayList<>();
                    if(smsRound.getStatus().equals(MarketSmsRound.STATUS.STARTING.value)){
                        List keys = this.redisService.keys(RedisKey.ROUND_SKU_STOCK_KEY + p.getId());
                        for (Object o:keys){
                            marketSmsRoundProducts.add((MarketSmsRoundProduct)o);
                        }
                    }else{
                        marketSmsRoundProducts = this.roundService.selectSkuByRoundIdProductId(roundId, p.getId());
                    }
                    Map<Long, List<MarketSmsRoundProduct>> collect = marketSmsRoundProducts.stream().collect(Collectors.groupingBy(MarketSmsRoundProduct::getSkuId));
                    List<Long> skuIds = marketSmsRoundProducts.stream().map(MarketSmsRoundProduct::getSkuId).collect(Collectors.toList());
                    if(!CollectionUtils.isEmpty(skuIds)){
                        List<PmsSkuStockDTO> skuStockDTOS = new ArrayList<>();
                        PmsSkuStockExample skuExample = new PmsSkuStockExample();
                        skuExample.createCriteria().andIdIn(skuIds);
                        List<PmsSkuStock> pmsSkuStocks = this.stockMapper.selectByExample(skuExample);
                        for (PmsSkuStock sku:pmsSkuStocks) {
                            PmsSkuStockDTO stockDTO = new PmsSkuStockDTO();
                            BeanUtils.copyProperties(sku,stockDTO);
                            Long key = sku.getId();
                            MarketSmsRoundProduct marketSmsRoundProduct = collect.get(key).get(0);
                            stockDTO.setNum(marketSmsRoundProduct.getNum());
                            stockDTO.setActivityPrice(marketSmsRoundProduct.getActivityPrice());
                            stockDTO.setGroupSize(marketSmsRoundProduct.getGroupSize());
                            stockDTO.setResidueNum(marketSmsRoundProduct.getResidueNum());
                            stockDTO.setType(marketSmsRoundProduct.getType());
                            stockDTO.setMarketProductId(marketSmsRoundProduct.getId());
                            skuStockDTOS.add(stockDTO);
                        }
                        productDTO.setSkuList(skuStockDTOS);
                    }
                    res.add(productDTO);
                }

            }
        }
        MarketSmsRoundProductExample roundProductExample = new MarketSmsRoundProductExample();
        roundProductExample.createCriteria().andRoundIdEqualTo(roundId);
        List<MarketSmsRoundProduct> marketSmsRoundProducts = roundProductMapper.selectByExample(roundProductExample);
        if(!CollectionUtils.isEmpty(marketSmsRoundProducts)){
            skuIdList = marketSmsRoundProducts.stream().map(MarketSmsRoundProduct::getSkuId).collect(Collectors.toList());
        }
        CommonPage<PmsProductDTO> result = new CommonPage<>();
        BeanUtils.copyProperties(longCommonPage,result);
        result.setList(res);
        returnMap.put("page",result);
        returnMap.put("skuIds",skuIdList);
        return CommonResult.success(returnMap);
    }

    @ApiOperation("获取商品下已选sku信息")
    @RequestMapping(value = "/listSkuByRoundIdAndProductId", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MarketSmsRoundProductDTO>> list(Long roundId, Long productId) {
        List<MarketSmsRoundProductDTO> pmsSkus = new ArrayList<>();
        List<MarketSmsRoundProduct> marketSmsRoundProducts = this.roundService.selectSkuByRoundIdProductId(roundId, productId);
        if(!CollectionUtils.isEmpty(marketSmsRoundProducts)){
            List<Long> skuIds = marketSmsRoundProducts.stream().map(MarketSmsRoundProduct::getSkuId).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(skuIds)){
                PmsSkuStockExample example = new PmsSkuStockExample();
                example.createCriteria().andIdIn(skuIds);
                List<PmsSkuStock> pmsSkuStocks = this.stockMapper.selectByExample(example);
                if(!CollectionUtils.isEmpty(pmsSkuStocks)){
                    Map<Long, List<PmsSkuStock>> collect = pmsSkuStocks.stream().collect(Collectors.groupingBy(PmsSkuStock::getId));
                    for (MarketSmsRoundProduct e:marketSmsRoundProducts) {
                        MarketSmsRoundProductDTO dto = new MarketSmsRoundProductDTO();
                        BeanUtils.copyProperties(e,dto);
                        List<PmsSkuStock> skus = collect.get(e.getSkuId());
                        if(!CollectionUtils.isEmpty(skus)){
                            PmsSkuStock pmsSkuStock = skus.get(0);
                            dto.setSpData(pmsSkuStock.getSpData());
                            dto.setActivityLockStock(pmsSkuStock.getActivityLockStock());
                            dto.setStock(pmsSkuStock.getStock());
                            dto.setLockStock(pmsSkuStock.getLockStock());
                            dto.setSkuCode(pmsSkuStock.getSkuCode());
                            pmsSkus.add(dto);
                        }
                    }
                }
            }
        }
        return CommonResult.success(pmsSkus);
    }

    @ApiOperation("分页获取全部可选场次")
    @RequestMapping(value = "/selectList", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public CommonResult<CommonPage<MarketSmsRound>> selectList(@CurrentUser UmsAdmin currentUser, @RequestBody MarketSmsRoundDTO dto) {
        dto.setUserId(currentUser.getId());
        CommonPage<MarketSmsRound> select = this.roundService.select(dto);
        return CommonResult.success(select);
    }

    @ApiOperation("分页获取商品列表")
    @RequestMapping(value = "/selectList", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<PmsProductDTO>> selectProductList(@CurrentUser UmsAdmin currentUser
            , @RequestParam(required = false,defaultValue = "1") Integer pageNum
            , @RequestParam(required = false,defaultValue = "5") Integer pageSize
            , @RequestParam(required = false) String  productName) {
        CommonPage<PmsProductDTO> pmsSkuStockDTOCommonPage = new CommonPage<>();
        UmsStoreExample example = new UmsStoreExample();
        example.createCriteria().andUserIdEqualTo(currentUser.getId());
        List<UmsStore> umsStores = this.storeMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(umsStores)){
            UmsStore umsStore = umsStores.get(0);
            PageHelper.startPage(pageNum,pageSize);
            List<PmsProductDTO> list = this.skuStockDao.selectForActivity(umsStore.getId(), productName);
            pmsSkuStockDTOCommonPage = CommonPage.restPage(list);
            List<PmsProductDTO> list1 = pmsSkuStockDTOCommonPage.getList();
            for (PmsProductDTO dto:list1) {
                List<PmsSkuStockDTO> skus = new ArrayList<>();
                List<PmsSkuStock> pmsSkuStocks = this.skuStockDao.selectSkuForActivity(dto.getId());
                if(!CollectionUtils.isEmpty(pmsSkuStocks)){
                    for (PmsSkuStock stockDTO: pmsSkuStocks) {
                        PmsSkuStockDTO skuStockDTO = new PmsSkuStockDTO();
                        BeanUtils.copyProperties(stockDTO,skuStockDTO);
                        skus.add(skuStockDTO);
                    }
                }
                dto.setSkuList(skus);
            }
            pmsSkuStockDTOCommonPage.setList(list1);
        }
        return CommonResult.success(pmsSkuStockDTOCommonPage);
    }
}